<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">
        <form class="layui-form layui-form-pane" action="">
            <div class="layui-form-item">
                <div class="received" style="height: 420px; overflow: scroll;">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <textarea name="msg" placeholder="请输入内容"
                    class="layui-textarea">{"action":"showInfo","data":""}</textarea>
            </div>
            <div class="layui-form-item">
                <input class="layui-btn" lay-submit="" lay-filter="sendBtn" type="submit" value="发送" disabled />
                <input class="layui-btn" id="receivedClear" type="button" value="清空" />
                <input class="layui-btn layui-btn-normal" id="apiPushBtn" type="button" value="API推送" disabled />
            </div>
        </form>
    </div>
</div>
<script>
    layui.use([], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            http = layui.http,
            form = layui.form;

        (function ($) {
            $.extend({
                WebSocketHelper: function (protocol, host, port) {
                    var _this = this;
                    var handlers = {};
                    var ws = new WebSocket(protocol + "://" + host + ":" + port);
                    ws.onopen = function () {
                        if (_this.onopen) {
                            _this.onopen();
                        }
                    };
                    ws.onmessage = function (evt) {
                        if (_this.onmessage) {
                            _this.onmessage(evt.data);
                        }
                        var response = JSON.parse(evt.data);
                        if (response.type == 0) {
                            var handler_key = "request-" + response.reqid;
                            var handler = handlers[handler_key];
                            if (handler) {
                                handler(response);
                                delete handlers[handler_key];
                            }
                        }
                        if (response.type == 1) {
                            var handler_key = response.action;
                            var handler = handlers[handler_key];
                            if (handler) {
                                handler(response);
                            }
                        }
                    };
                    this.register = function (action, handler) {
                        handlers[action] = handler;
                    };
                    this.request = function (action, data, callback) {
                        if (!data) {
                            data = {};
                        }
                        if (action) {
                            data["action"] = action;
                        }
                        data["reqid"] = (new Date()).getTime() + "-" + Math.random().toString().substr(2);
                        _this.register("request-" + data["reqid"], callback);
                        if (ws && ws.readyState === 1) {
                            console.log("发送消息内容:");
                            console.log(data);
                            ws.send(JSON.stringify(data));
                        } else {
                            if (_this.onsenderror) {
                                _this.onsenderror(ws.readyState);
                            }
                        }
                    };
                }
            });
        })(layui.jquery);


        //建立连接
        http.ajaxPost('/admin/Admin/msgServer', {}, function (data) {
            window.ws_admin_login = new $.WebSocketHelper(data.protocol, data.host, data.port);
            window.ws_admin_login.onopen = function () {
                //登录成功后，才会收到服务器推送信息
                window.ws_admin_login.request("tokenLogin", { token: data.token }, function (rsp) {
                    console.log("请求响应（登录结果）:");
                    console.log(rsp);
                    //注册客户端成功后才允许发送信息
                    if (rsp.code === 0) {
                        $('input[lay-filter="sendBtn"]').removeAttr("disabled");
                        $('#apiPushBtn').removeAttr("disabled");
                    } else {
                        layer.msg(rsp.msg, {}, function () { });
                    }
                });
            };
            window.ws_admin_login.onmessage = function (msg) {
                $('.received').append($("<p></p>").text(msg));
            };
            window.ws_admin_login.onsenderror = function (msg) {
                layer.msg('服务器连接中断', {}, function () {
                    location.reload();
                });
            };
            //注册服务器推送消息的处理方法
            window.ws_admin_login.register("apiPush", function (data) {
                console.log("API推送:");
                console.log(data);
            });
        });

        //发送消息事件
        form.on('submit(sendBtn)', function (data) {
            window.ws_admin_login.request("", JSON.parse(data.field.msg), function (rsp) {
                console.log("请求响应（自定义请求）：");
                console.log(rsp);
            });
            return false;
        });

        //清空接收
        $('#receivedClear').click(function () {
            $('.received').html('');
        });

        //API推送
        $('#apiPushBtn').click(function () {
            http.ajaxPost('/admin/Admin/msgPush', {}, function (data) {
                //
            });
        });
    });
</script>